home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 1.iso / util / tgrep20.zip / DFA.C < prev    next >
C/C++ Source or Header  |  1994-04-01  |  66KB  |  2,505 lines

  1. /* dfa.c - deterministic extended regexp routines for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written June, 1988 by Mike Haertel
  19.    Modified July, 1988 by Arthur David Olson to assist BMG speedups  */
  20.  
  21. #include <assert.h>
  22. #include <ctype.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #undef index
  27. #define index strchr
  28. #ifndef isgraph
  29. #define isgraph(C) (isprint(C) && !isspace(C))
  30. #endif
  31.  
  32. #ifdef isascii
  33. #define ISALPHA(C) (isascii(C) && isalpha(C))
  34. #define ISUPPER(C) (isascii(C) && isupper(C))
  35. #define ISLOWER(C) (isascii(C) && islower(C))
  36. #define ISDIGIT(C) (isascii(C) && isdigit(C))
  37. #define ISXDIGIT(C) (isascii(C) && isxdigit(C))
  38. #define ISSPACE(C) (isascii(C) && isspace(C))
  39. #define ISPUNCT(C) (isascii(C) && ispunct(C))
  40. #define ISALNUM(C) (isascii(C) && isalnum(C))
  41. #define ISPRINT(C) (isascii(C) && isprint(C))
  42. #define ISGRAPH(C) (isascii(C) && isgraph(C))
  43. #define ISCNTRL(C) (isascii(C) && iscntrl(C))
  44. #else
  45. #define ISALPHA(C) isalpha(C)
  46. #define ISUPPER(C) isupper(C)
  47. #define ISLOWER(C) islower(C)
  48. #define ISDIGIT(C) isdigit(C)
  49. #define ISXDIGIT(C) isxdigit(C)
  50. #define ISSPACE(C) isspace(C)
  51. #define ISPUNCT(C) ispunct(C)
  52. #define ISALNUM(C) isalnum(C)
  53. #define ISPRINT(C) isprint(C)
  54. #define ISGRAPH(C) isgraph(C)
  55. #define ISCNTRL(C) iscntrl(C)
  56. #endif
  57.  
  58. #include "dfa.h"
  59. #include "regex.h"
  60.  
  61. typedef void *ptr_t;
  62.  
  63. static void    dfamust(struct dfa *);
  64.  
  65. static ptr_t
  66. xcalloc(
  67.      int n,
  68.      size_t s)
  69. {
  70.   ptr_t r = calloc(n, s);
  71.  
  72.   if (!r)
  73.     dfaerror("Memory exhausted");
  74.   return r;
  75. }
  76.  
  77. static ptr_t
  78. xmalloc(
  79.      size_t n)
  80. {
  81.   ptr_t r = malloc(n);
  82.  
  83.   assert(n != 0);
  84.   if (!r)
  85.     dfaerror("Memory exhausted");
  86.   return r;
  87. }
  88.  
  89. static ptr_t
  90. xrealloc(
  91.      ptr_t p,
  92.      size_t n)
  93. {
  94.   ptr_t r = realloc(p, n);
  95.  
  96.   assert(n != 0);
  97.   if (!r)
  98.     dfaerror("Memory exhausted");
  99.   return r;
  100. }
  101.  
  102. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((n), sizeof (t)))
  103. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  104. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  105.  
  106. /* Reallocate an array of type t if nalloc is too small for index. */
  107. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  108.   if ((index) >= (nalloc))              \
  109.     {                          \
  110.       while ((index) >= (nalloc))          \
  111.     (nalloc) *= 2;                  \
  112.       REALLOC(p, t, nalloc);              \
  113.     }
  114.  
  115. #ifdef DEBUG
  116.  
  117. static void
  118. prtok(t)
  119.      token t;
  120. {
  121.   char *s;
  122.  
  123.   if (t < 0)
  124.     fprintf(stderr, "END");
  125.   else if (t < NOTCHAR)
  126.     fprintf(stderr, "%c", t);
  127.   else
  128.     {
  129.       switch (t)
  130.     {
  131.     case EMPTY: s = "EMPTY"; break;
  132.     case BACKREF: s = "BACKREF"; break;
  133.     case BEGLINE: s = "BEGLINE"; break;
  134.     case ENDLINE: s = "ENDLINE"; break;
  135.     case BEGWORD: s = "BEGWORD"; break;
  136.     case ENDWORD: s = "ENDWORD"; break;
  137.     case LIMWORD: s = "LIMWORD"; break;
  138.     case NOTLIMWORD: s = "NOTLIMWORD"; break;
  139.     case QMARK: s = "QMARK"; break;
  140.     case STAR: s = "STAR"; break;
  141.     case PLUS: s = "PLUS"; break;
  142.     case CAT: s = "CAT"; break;
  143.     case OR: s = "OR"; break;
  144.     case ORTOP: s = "ORTOP"; break;
  145.     case LPAREN: s = "LPAREN"; break;
  146.     case RPAREN: s = "RPAREN"; break;
  147.     default: s = "CSET"; break;
  148.     }
  149.       fprintf(stderr, "%s", s);
  150.     }
  151. }
  152. #endif /* DEBUG */
  153.  
  154. /* Stuff pertaining to charclasses. */
  155.  
  156. static int
  157. tstbit(
  158.      int b,
  159.      charclass c)
  160. {
  161.   return c[b / INTBITS] & 1 << b % INTBITS;
  162. }
  163.  
  164. static void
  165. setbit(
  166.      int b,
  167.      charclass c)
  168. {
  169.   c[b / INTBITS] |= 1 << b % INTBITS;
  170. }
  171.  
  172. static void
  173. clrbit(
  174.      int b,
  175.      charclass c)
  176. {
  177.   c[b / INTBITS] &= ~(1 << b % INTBITS);
  178. }
  179.  
  180. static void
  181. copyset(
  182.      charclass src,
  183.      charclass dst)
  184. {
  185.   int i;
  186.  
  187.   for (i = 0; i < CHARCLASS_INTS; ++i)
  188.     dst[i] = src[i];
  189. }
  190.  
  191. static void
  192. zeroset(
  193.      charclass s)
  194. {
  195.   int i;
  196.  
  197.   for (i = 0; i < CHARCLASS_INTS; ++i)
  198.     s[i] = 0;
  199. }
  200.  
  201. static void
  202. notset(
  203.      charclass s)
  204. {
  205.   int i;
  206.  
  207.   for (i = 0; i < CHARCLASS_INTS; ++i)
  208.     s[i] = ~s[i];
  209. }
  210.  
  211. static int
  212. equal(
  213.      charclass s1,
  214.      charclass s2)
  215. {
  216.   int i;
  217.  
  218.   for (i = 0; i < CHARCLASS_INTS; ++i)
  219.     if (s1[i] != s2[i])
  220.       return 0;
  221.   return 1;
  222. }
  223.  
  224. /* A pointer to the current dfa is kept here during parsing. */
  225. static struct dfa *dfa;
  226.  
  227. /* Find the index of charclass s in dfa->charclasses, or allocate a new charclass. */
  228. static int
  229. charclass_index(
  230.      charclass s)
  231. {
  232.   int i;
  233.  
  234.   for (i = 0; i < dfa->cindex; ++i)
  235.     if (equal(s, dfa->charclasses[i]))
  236.       return i;
  237.   REALLOC_IF_NECESSARY(dfa->charclasses, charclass, dfa->calloc, dfa->cindex);
  238.   ++dfa->cindex;
  239.   copyset(s, dfa->charclasses[i]);
  240.   return i;
  241. }
  242.  
  243. /* Syntax bits controlling the behavior of the lexical analyzer. */
  244. static int syntax_bits, syntax_bits_set;
  245.  
  246. /* Flag for case-folding letters into sets. */
  247. static int case_fold;
  248.  
  249. /* Entry point to set syntax options. */
  250. void
  251. dfasyntax(
  252.      int bits,
  253.      int fold)
  254. {
  255.   syntax_bits_set = 1;
  256.   syntax_bits = bits;
  257.   case_fold = fold;
  258. }
  259.  
  260. /* Lexical analyzer.  All the dross that deals with the obnoxious
  261.    GNU Regex syntax bits is located here.  The poor, suffering
  262.    reader is referred to the GNU Regex documentation for the
  263.    meaning of the @#%!@#%^!@ syntax bits. */
  264.  
  265. static char *lexstart;        /* Pointer to beginning of input string. */
  266. static char *lexptr;        /* Pointer to next input character. */
  267. static lexleft;            /* Number of characters remaining. */
  268. static token lasttok;        /* Previous token returned; initially END. */
  269. static int laststart;        /* True if we're separated from beginning or (, |
  270.                    only by zero-width characters. */
  271. static int parens;        /* Count of outstanding left parens. */
  272. static int minrep, maxrep;    /* Repeat counts for {m,n}. */
  273.  
  274. /* Note that characters become unsigned here. */
  275. #define FETCH(c, eoferr)             \
  276.   {                         \
  277.     if (! lexleft)                 \
  278.       if (eoferr != 0)                 \
  279.     dfaerror(eoferr);            \
  280.       else                     \
  281.     return END;                 \
  282.     (c) = (unsigned char) *lexptr++;  \
  283.     --lexleft;                     \
  284.   }
  285.  
  286. #define FUNC(F, P) static int F(int c) { return P(c); }
  287.  
  288. FUNC(is_alpha, ISALPHA)
  289. FUNC(is_upper, ISUPPER)
  290. FUNC(is_lower, ISLOWER)
  291. FUNC(is_digit, ISDIGIT)
  292. FUNC(is_xdigit, ISXDIGIT)
  293. FUNC(is_space, ISSPACE)
  294. FUNC(is_punct, ISPUNCT)
  295. FUNC(is_alnum, ISALNUM)
  296. FUNC(is_print, ISPRINT)
  297. FUNC(is_graph, ISGRAPH)
  298. FUNC(is_cntrl, ISCNTRL)
  299.  
  300. /* The following list maps the names of the Posix named character classes
  301.    to predicate functions that determine whether a given character is in
  302.    the class.  The leading [ has already been eaten by the lexical analyzer. */
  303. static struct {
  304.   char *name;
  305.   int (*pred)(int);
  306. } prednames[] = {
  307.   ":alpha:]", is_alpha,
  308.   ":upper:]", is_upper,
  309.   ":lower:]", is_lower,
  310.   ":digit:]", is_digit,
  311.   ":xdigit:]", is_xdigit,
  312.   ":space:]", is_space,
  313.   ":punct:]", is_punct,
  314.   ":alnum:]", is_alnum,
  315.   ":print:]", is_print,
  316.   ":graph:]", is_graph,
  317.   ":cntrl:]", is_cntrl,
  318.   0
  319. };
  320.  
  321. static int
  322. looking_at(
  323.      char *s)
  324. {
  325.   int len;
  326.  
  327.   len = strlen(s);
  328.   if (lexleft < len)
  329.     return 0;
  330.   return strncmp(s, lexptr, len) == 0;
  331. }
  332.  
  333. static token
  334. lex(void)
  335. {
  336.   token c, c1, c2;
  337.   int backslash = 0, invert;
  338.   charclass ccl;
  339.   int i;
  340.  
  341.   /* Basic plan: We fetch a character.  If it's a backslash,
  342.      we set the backslash flag and go through the loop again.
  343.      On the plus side, this avoids having a duplicate of the
  344.      main switch inside the backslash case.  On the minus side,
  345.      it means that just about every case begins with
  346.      "if (backslash) ...".  */
  347.   for (i = 0; i < 2; ++i)
  348.     {
  349.       FETCH(c, 0);
  350.       switch (c)
  351.     {
  352.     case '\\':
  353.       if (backslash)
  354.         goto normal_char;
  355.       if (lexleft == 0)
  356.         dfaerror("Unfinished \\ escape");
  357.       backslash = 1;
  358.       break;
  359.  
  360.     case '^':
  361.       if (backslash)
  362.         goto normal_char;
  363.       if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  364.           || lasttok == END
  365.           || lasttok == LPAREN
  366.           || lasttok == OR)
  367.         return lasttok = BEGLINE;
  368.       goto normal_char;
  369.  
  370.     case '$':
  371.       if (backslash)
  372.         goto normal_char;
  373.       if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  374.           || lexleft == 0
  375.           || (syntax_bits & RE_NO_BK_PARENS
  376.           ? lexleft > 0 && *lexptr == ')'
  377.           : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == ')')
  378.           || (syntax_bits & RE_NO_BK_VBAR
  379.           ? lexleft > 0 && *lexptr == '|'
  380.           : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == '|')
  381.           || ((syntax_bits & RE_NEWLINE_ALT)
  382.               && lexleft > 0 && *lexptr == '\n'))
  383.         return lasttok = ENDLINE;
  384.       goto normal_char;
  385.  
  386.     case '1':
  387.     case '2':
  388.     case '3':
  389.     case '4':
  390.     case '5':
  391.     case '6':
  392.     case '7':
  393.     case '8':
  394.     case '9':
  395.       if (backslash && !(syntax_bits & RE_NO_BK_REFS))
  396.         {
  397.           laststart = 0;
  398.           return lasttok = BACKREF;
  399.         }
  400.       goto normal_char;
  401.  
  402.     case '<':
  403.       if (backslash)
  404.         return lasttok = BEGWORD;
  405.       goto normal_char;
  406.  
  407.     case '>':
  408.       if (backslash)
  409.         return lasttok = ENDWORD;
  410.       goto normal_char;
  411.  
  412.     case 'b':
  413.       if (backslash)
  414.         return lasttok = LIMWORD;
  415.       goto normal_char;
  416.  
  417.     case 'B':
  418.       if (backslash)
  419.         return lasttok = NOTLIMWORD;
  420.       goto normal_char;
  421.  
  422.     case '?':
  423.       if (syntax_bits & RE_LIMITED_OPS)
  424.         goto normal_char;
  425.       if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  426.         goto normal_char;
  427.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  428.         goto normal_char;
  429.       return lasttok = QMARK;
  430.  
  431.     case '*':
  432.       if (backslash)
  433.         goto normal_char;
  434.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  435.         goto normal_char;
  436.       return lasttok = STAR;
  437.  
  438.     case '+':
  439.       if (syntax_bits & RE_LIMITED_OPS)
  440.         goto normal_char;
  441.       if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  442.         goto normal_char;
  443.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  444.         goto normal_char;
  445.       return lasttok = PLUS;
  446.  
  447.     case '{':
  448.       if (!(syntax_bits & RE_INTERVALS))
  449.         goto normal_char;
  450.       if (backslash != ((syntax_bits & RE_NO_BK_BRACES) == 0))
  451.         goto normal_char;
  452.       minrep = maxrep = 0;
  453.       /* Cases:
  454.          {M} - exact count
  455.          {M,} - minimum count, maximum is infinity
  456.          {,M} - 0 through M
  457.          {M,N} - M through N */
  458.       FETCH(c, "unfinished repeat count");
  459.       if (ISDIGIT(c))
  460.         {
  461.           minrep = c - '0';
  462.           for (;;)
  463.         {
  464.           FETCH(c, "unfinished repeat count");
  465.           if (!ISDIGIT(c))
  466.             break;
  467.           minrep = 10 * minrep + c - '0';
  468.         }
  469.         }
  470.       else if (c != ',')
  471.         dfaerror("malformed repeat count");
  472.       if (c == ',')
  473.         for (;;)
  474.           {
  475.         FETCH(c, "unfinished repeat count");
  476.         if (!ISDIGIT(c))
  477.           break;
  478.         maxrep = 10 * maxrep + c - '0';
  479.           }
  480.       else
  481.         maxrep = minrep;
  482.       if (!(syntax_bits & RE_NO_BK_BRACES))
  483.         {
  484.           if (c != '\\')
  485.         dfaerror("malformed repeat count");
  486.           FETCH(c, "unfinished repeat count");
  487.         }
  488.       if (c != '}')
  489.         dfaerror("malformed repeat count");
  490.       laststart = 0;
  491.       return lasttok = REPMN;
  492.  
  493.     case '|':
  494.       if (syntax_bits & RE_LIMITED_OPS)
  495.         goto normal_char;
  496.       if (backslash != ((syntax_bits & RE_NO_BK_VBAR) == 0))
  497.         goto normal_char;
  498.       laststart = 1;
  499.       return lasttok = OR;
  500.  
  501.     case '\n':
  502.       if (syntax_bits & RE_LIMITED_OPS
  503.           || backslash
  504.           || !(syntax_bits & RE_NEWLINE_ALT))
  505.         goto normal_char;
  506.       laststart = 1;
  507.       return lasttok = OR;
  508.  
  509.     case '(':
  510.       if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  511.         goto normal_char;
  512.       ++parens;
  513.       laststart = 1;
  514.       return lasttok = LPAREN;
  515.  
  516.     case ')':
  517.       if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  518.         goto normal_char;
  519.       if (parens == 0 && syntax_bits & RE_UNMATCHED_RIGHT_PAREN_ORD)
  520.         goto normal_char;
  521.       --parens;
  522.       laststart = 0;
  523.       return lasttok = RPAREN;
  524.  
  525.     case '.':
  526.       if (backslash)
  527.         goto normal_char;
  528.       zeroset(ccl);
  529.       notset(ccl);
  530.       if (!(syntax_bits & RE_DOT_NEWLINE))
  531.         clrbit('\n', ccl);
  532.       if (syntax_bits & RE_DOT_NOT_NULL)
  533.         clrbit('\0', ccl);
  534.       laststart = 0;
  535.       return lasttok = CSET + charclass_index(ccl);
  536.  
  537.     case 'w':
  538.     case 'W':
  539.       if (!backslash)
  540.         goto normal_char;
  541.       zeroset(ccl);
  542.       for (c2 = 0; c2 < NOTCHAR; ++c2)
  543.         if (ISALNUM(c2))
  544.           setbit(c2, ccl);
  545.       if (c == 'W')
  546.         notset(ccl);
  547.       laststart = 0;
  548.       return lasttok = CSET + charclass_index(ccl);
  549.     
  550.     case '[':
  551.       if (backslash)
  552.         goto normal_char;
  553.       zeroset(ccl);
  554.       FETCH(c, "Unbalanced [");
  555.       if (c == '^')
  556.         {
  557.           FETCH(c, "Unbalanced [");
  558.           invert = 1;
  559.         }
  560.       else
  561.         invert = 0;
  562.       do
  563.         {
  564.           /* Nobody ever said this had to be fast. :-)
  565.          Note that if we're looking at some other [:...:]
  566.          construct, we just treat it as a bunch of ordinary
  567.          characters.  We can do this because we assume
  568.          regex has checked for syntax errors before
  569.          dfa is ever called. */
  570.           if (c == '[' && (syntax_bits & RE_CHAR_CLASSES))
  571.         for (c1 = 0; prednames[c1].name; ++c1)
  572.           if (looking_at(prednames[c1].name))
  573.             {
  574.               for (c2 = 0; c2 < NOTCHAR; ++c2)
  575.             if ((*prednames[c1].pred)(c2))
  576.               setbit(c2, ccl);
  577.               lexptr += strlen(prednames[c1].name);
  578.               lexleft -= strlen(prednames[c1].name);
  579.               FETCH(c1, "Unbalanced [");
  580.               goto skip;
  581.             }
  582.           if (c == '\\' && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  583.         FETCH(c, "Unbalanced [");
  584.           FETCH(c1, "Unbalanced [");
  585.           if (c1 == '-')
  586.         {
  587.           FETCH(c2, "Unbalanced [");
  588.           if (c2 == ']')
  589.             {
  590.               /* In the case [x-], the - is an ordinary hyphen,
  591.              which is left in c1, the lookahead character. */
  592.               --lexptr;
  593.               ++lexleft;
  594.               c2 = c;
  595.             }
  596.           else
  597.             {
  598.               if (c2 == '\\'
  599.               && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  600.             FETCH(c2, "Unbalanced [");
  601.               FETCH(c1, "Unbalanced [");
  602.             }
  603.         }
  604.           else
  605.         c2 = c;
  606.           while (c <= c2)
  607.         {
  608.           setbit(c, ccl);
  609.           if (case_fold)
  610.             if (ISUPPER(c))
  611.               setbit(tolower(c), ccl);
  612.             else if (ISLOWER(c))
  613.               setbit(toupper(c), ccl);
  614.           ++c;
  615.         }
  616.         skip:
  617.           ;
  618.         }
  619.       while ((c = c1) != ']');
  620.       if (invert)
  621.         {
  622.           notset(ccl);
  623.           if (syntax_bits & RE_HAT_LISTS_NOT_NEWLINE)
  624.         clrbit('\n', ccl);
  625.         }
  626.       laststart = 0;
  627.       return lasttok = CSET + charclass_index(ccl);
  628.  
  629.     default:
  630.     normal_char:
  631.       laststart = 0;
  632.       if (case_fold && ISALPHA(c))
  633.         {
  634.           zeroset(ccl);
  635.           setbit(c, ccl);
  636.           if (isupper(c))
  637.         setbit(tolower(c), ccl);
  638.           else
  639.         setbit(toupper(c), ccl);
  640.           return lasttok = CSET + charclass_index(ccl);
  641.         }
  642.       return c;
  643.     }
  644.     }
  645.  
  646.   /* The above loop should consume at most a backslash
  647.      and some other character. */
  648.   abort();
  649. }
  650.  
  651. /* Recursive descent parser for regular expressions. */
  652.  
  653. static token tok;        /* Lookahead token. */
  654. static depth;            /* Current depth of a hypothetical stack
  655.                    holding deferred productions.  This is
  656.                    used to determine the depth that will be
  657.                    required of the real stack later on in
  658.                    dfaanalyze(). */
  659.  
  660. /* Add the given token to the parse tree, maintaining the depth count and
  661.    updating the maximum depth if necessary. */
  662. static void
  663. addtok(
  664.      token t)
  665. {
  666.   REALLOC_IF_NECESSARY(dfa->tokens, token, dfa->talloc, dfa->tindex);
  667.   dfa->tokens[dfa->tindex++] = t;
  668.  
  669.   switch (t)
  670.     {
  671.     case QMARK:
  672.     case STAR:
  673.     case PLUS:
  674.       break;
  675.  
  676.     case CAT:
  677.     case OR:
  678.     case ORTOP:
  679.       --depth;
  680.       break;
  681.  
  682.     default:
  683.       ++dfa->nleaves;
  684.     case EMPTY:
  685.       ++depth;
  686.       break;
  687.     }
  688.   if (depth > dfa->depth)
  689.     dfa->depth = depth;
  690. }
  691.  
  692. /* The grammar understood by the parser is as follows.
  693.  
  694.    regexp:
  695.      regexp OR branch
  696.      branch
  697.  
  698.    branch:
  699.      branch closure
  700.      closure
  701.  
  702.    closure:
  703.      closure QMARK
  704.      closure STAR
  705.      closure PLUS
  706.      atom
  707.  
  708.    atom:
  709.      <normal character>
  710.      CSET
  711.      BACKREF
  712.      BEGLINE
  713.      ENDLINE
  714.      BEGWORD
  715.      ENDWORD
  716.      LIMWORD
  717.      NOTLIMWORD
  718.      <empty>
  719.  
  720.    The parser builds a parse tree in postfix form in an array of tokens. */
  721.  
  722. static void regexp(int);
  723.  
  724. static void
  725. atom(void)
  726. {
  727.   if ((tok >= 0 && tok < NOTCHAR) || tok >= CSET || tok == BACKREF
  728.       || tok == BEGLINE || tok == ENDLINE || tok == BEGWORD
  729.       || tok == ENDWORD || tok == LIMWORD || tok == NOTLIMWORD)
  730.     {
  731.       addtok(tok);
  732.       tok = lex();
  733.     }
  734.   else if (tok == LPAREN)
  735.     {
  736.       tok = lex();
  737.       regexp(0);
  738.       if (tok != RPAREN)
  739.     dfaerror("Unbalanced (");
  740.       tok = lex();
  741.     }
  742.   else
  743.     addtok(EMPTY);
  744. }
  745.  
  746. /* Return the number of tokens in the given subexpression. */
  747. static int
  748. nsubtoks(int tindex)
  749. {
  750.   int ntoks1;
  751.  
  752.   switch (dfa->tokens[tindex - 1])
  753.     {
  754.     default:
  755.       return 1;
  756.     case QMARK:
  757.     case STAR:
  758.     case PLUS:
  759.       return 1 + nsubtoks(tindex - 1);
  760.     case CAT:
  761.     case OR:
  762.     case ORTOP:
  763.       ntoks1 = nsubtoks(tindex - 1);
  764.       return 1 + ntoks1 + nsubtoks(tindex - 1 - ntoks1);
  765.     }
  766. }
  767.  
  768. /* Copy the given subexpression to the top of the tree. */
  769. static void
  770. copytoks(
  771.      int tindex, int ntokens)
  772. {
  773.   int i;
  774.  
  775.   for (i = 0; i < ntokens; ++i)
  776.     addtok(dfa->tokens[tindex + i]);
  777. }
  778.  
  779. static void
  780. closure(void)
  781. {
  782.   int tindex, ntokens, i;
  783.  
  784.   atom();
  785.   while (tok == QMARK || tok == STAR || tok == PLUS || tok == REPMN)
  786.     if (tok == REPMN)
  787.       {
  788.     ntokens = nsubtoks(dfa->tindex);
  789.     tindex = dfa->tindex - ntokens;
  790.     if (maxrep == 0)
  791.       addtok(PLUS);
  792.     if (minrep == 0)
  793.       addtok(QMARK);
  794.     for (i = 1; i < minrep; ++i)
  795.       {
  796.         copytoks(tindex, ntokens);
  797.         addtok(CAT);
  798.       }
  799.     for (; i < maxrep; ++i)
  800.       {
  801.         copytoks(tindex, ntokens);
  802.         addtok(QMARK);
  803.         addtok(CAT);
  804.       }
  805.     tok = lex();
  806.       }
  807.     else
  808.       {
  809.     addtok(tok);
  810.     tok = lex();
  811.       }
  812. }
  813.  
  814. static void
  815. branch(void)
  816. {
  817.   closure();
  818.   while (tok != RPAREN && tok != OR && tok >= 0)
  819.     {
  820.       closure();
  821.       addtok(CAT);
  822.     }
  823. }
  824.  
  825. static void
  826. regexp(toplevel)
  827.      int toplevel;
  828. {
  829.   branch();
  830.   while (tok == OR)
  831.     {
  832.       tok = lex();
  833.       branch();
  834.       if (toplevel)
  835.     addtok(ORTOP);
  836.       else
  837.     addtok(OR);
  838.     }
  839. }
  840.  
  841. /* Main entry point for the parser.  S is a string to be parsed, len is the
  842.    length of the string, so s can include NUL characters.  D is a pointer to
  843.    the struct dfa to parse into. */
  844. void
  845. dfaparse(s, len, d)
  846.      char *s;
  847.      size_t len;
  848.      struct dfa *d;
  849.  
  850. {
  851.   dfa = d;
  852.   lexstart = lexptr = s;
  853.   lexleft = len;
  854.   lasttok = END;
  855.   laststart = 1;
  856.   parens = 0;
  857.  
  858.   if (! syntax_bits_set)
  859.     dfaerror("No syntax specified");
  860.  
  861.   tok = lex();
  862.   depth = d->depth;
  863.  
  864.   regexp(1);
  865.  
  866.   if (tok != END)
  867.     dfaerror("Unbalanced )");
  868.  
  869.   addtok(END - d->nregexps);
  870.   addtok(CAT);
  871.  
  872.   if (d->nregexps)
  873.     addtok(ORTOP);
  874.  
  875.   ++d->nregexps;
  876. }
  877.  
  878. /* Some primitives for operating on sets of positions. */
  879.  
  880. /* Copy one set to another; the destination must be large enough. */
  881. static void
  882. copy(
  883.      position_set *src,
  884.      position_set *dst)
  885. {
  886.   int i;
  887.  
  888.   for (i = 0; i < src->nelem; ++i)
  889.     dst->elems[i] = src->elems[i];
  890.   dst->nelem = src->nelem;
  891. }
  892.  
  893. /* Insert a position in a set.  Position sets are maintained in sorted
  894.    order according to index.  If position already exists in the set with
  895.    the same index then their constraints are logically or'd together.
  896.    S->elems must point to an array large enough to hold the resulting set. */
  897. static void
  898. insert(
  899.      position p,
  900.      position_set *s)
  901. {
  902.   int i;
  903.   position t1, t2;
  904.  
  905.   for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  906.     ;
  907.   if (i < s->nelem && p.index == s->elems[i].index)
  908.     s->elems[i].constraint |= p.constraint;
  909.   else
  910.     {
  911.       t1 = p;
  912.       ++s->nelem;
  913.       while (i < s->nelem)
  914.     {
  915.       t2 = s->elems[i];
  916.       s->elems[i++] = t1;
  917.       t1 = t2;
  918.     }
  919.     }
  920. }
  921.  
  922. /* Merge two sets of positions into a third.  The result is exactly as if
  923.    the positions of both sets were inserted into an initially empty set. */
  924. static void
  925. merge(
  926.      position_set *s1,
  927.      position_set *s2,
  928.      position_set *m)
  929. {
  930.   int i = 0, j = 0;
  931.  
  932.   m->nelem = 0;
  933.   while (i < s1->nelem && j < s2->nelem)
  934.     if (s1->elems[i].index > s2->elems[j].index)
  935.       m->elems[m->nelem++] = s1->elems[i++];
  936.     else if (s1->elems[i].index < s2->elems[j].index)
  937.       m->elems[m->nelem++] = s2->elems[j++];
  938.     else
  939.       {
  940.     m->elems[m->nelem] = s1->elems[i++];
  941.     m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  942.       }
  943.   while (i < s1->nelem)
  944.     m->elems[m->nelem++] = s1->elems[i++];
  945.   while (j < s2->nelem)
  946.     m->elems[m->nelem++] = s2->elems[j++];
  947. }
  948.  
  949. /* Delete a position from a set. */
  950. static void
  951. delete(
  952.      position p,
  953.      position_set *s)
  954. {
  955.   int i;
  956.  
  957.   for (i = 0; i < s->nelem; ++i)
  958.     if (p.index == s->elems[i].index)
  959.       break;
  960.   if (i < s->nelem)
  961.     for (--s->nelem; i < s->nelem; ++i)
  962.       s->elems[i] = s->elems[i + 1];
  963. }
  964.  
  965. /* Find the index of the state corresponding to the given position set with
  966.    the given preceding context, or create a new state if there is no such
  967.    state.  Newline and letter tell whether we got here on a newline or
  968.    letter, respectively. */
  969. static int
  970. state_index(
  971.      struct dfa *d,
  972.      position_set *s,
  973.      int newline,
  974.      int letter)
  975. {
  976.   int hash = 0;
  977.   int constraint;
  978.   int i, j;
  979.  
  980.   newline = newline ? 1 : 0;
  981.   letter = letter ? 1 : 0;
  982.  
  983.   for (i = 0; i < s->nelem; ++i)
  984.     hash ^= s->elems[i].index + s->elems[i].constraint;
  985.  
  986.   /* Try to find a state that exactly matches the proposed one. */
  987.   for (i = 0; i < d->sindex; ++i)
  988.     {
  989.       if (hash != d->states[i].hash || s->nelem != d->states[i].elems.nelem
  990.       || newline != d->states[i].newline || letter != d->states[i].letter)
  991.     continue;
  992.       for (j = 0; j < s->nelem; ++j)
  993.     if (s->elems[j].constraint
  994.         != d->states[i].elems.elems[j].constraint
  995.         || s->elems[j].index != d->states[i].elems.elems[j].index)
  996.       break;
  997.       if (j == s->nelem)
  998.     return i;
  999.     }
  1000.  
  1001.   /* We'll have to create a new state. */
  1002.   REALLOC_IF_NECESSARY(d->states, dfa_state, d->salloc, d->sindex);
  1003.   d->states[i].hash = hash;
  1004.   MALLOC(d->states[i].elems.elems, position, s->nelem);
  1005.   copy(s, &d->states[i].elems);
  1006.   d->states[i].newline = newline;
  1007.   d->states[i].letter = letter;
  1008.   d->states[i].backref = 0;
  1009.   d->states[i].constraint = 0;
  1010.   d->states[i].first_end = 0;
  1011.   for (j = 0; j < s->nelem; ++j)
  1012.     if (d->tokens[s->elems[j].index] < 0)
  1013.       {
  1014.     constraint = s->elems[j].constraint;
  1015.     if (SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  1016.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  1017.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  1018.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  1019.       d->states[i].constraint |= constraint;
  1020.     if (! d->states[i].first_end)
  1021.       d->states[i].first_end = d->tokens[s->elems[j].index];
  1022.       }
  1023.     else if (d->tokens[s->elems[j].index] == BACKREF)
  1024.       {
  1025.     d->states[i].constraint = NO_CONSTRAINT;
  1026.     d->states[i].backref = 1;
  1027.       }
  1028.  
  1029.   ++d->sindex;
  1030.  
  1031.   return i;
  1032. }
  1033.  
  1034. /* Find the epsilon closure of a set of positions.  If any position of the set
  1035.    contains a symbol that matches the empty string in some context, replace
  1036.    that position with the elements of its follow labeled with an appropriate
  1037.    constraint.  Repeat exhaustively until no funny positions are left.
  1038.    S->elems must be large enough to hold the result. */
  1039. void
  1040. epsclosure(
  1041.      position_set *s,
  1042.      struct dfa *d)
  1043. {
  1044.   int i, j;
  1045.   int *visited;
  1046.   position p, old;
  1047.  
  1048.   MALLOC(visited, int, d->tindex);
  1049.   for (i = 0; i < d->tindex; ++i)
  1050.     visited[i] = 0;
  1051.  
  1052.   for (i = 0; i < s->nelem; ++i)
  1053.     if (d->tokens[s->elems[i].index] >= NOTCHAR
  1054.     && d->tokens[s->elems[i].index] != BACKREF
  1055.     && d->tokens[s->elems[i].index] < CSET)
  1056.       {
  1057.     old = s->elems[i];
  1058.     p.constraint = old.constraint;
  1059.     delete(s->elems[i], s);
  1060.     if (visited[old.index])
  1061.       {
  1062.         --i;
  1063.         continue;
  1064.       }
  1065.     visited[old.index] = 1;
  1066.     switch (d->tokens[old.index])
  1067.       {
  1068.       case BEGLINE:
  1069.         p.constraint &= BEGLINE_CONSTRAINT;
  1070.         break;
  1071.       case ENDLINE:
  1072.         p.constraint &= ENDLINE_CONSTRAINT;
  1073.         break;
  1074.       case BEGWORD:
  1075.         p.constraint &= BEGWORD_CONSTRAINT;
  1076.         break;
  1077.       case ENDWORD:
  1078.         p.constraint &= ENDWORD_CONSTRAINT;
  1079.         break;
  1080.       case LIMWORD:
  1081.         p.constraint &= LIMWORD_CONSTRAINT;
  1082.         break;
  1083.       case NOTLIMWORD:
  1084.         p.constraint &= NOTLIMWORD_CONSTRAINT;
  1085.         break;
  1086.       default:
  1087.         break;
  1088.       }
  1089.     for (j = 0; j < d->follows[old.index].nelem; ++j)
  1090.       {
  1091.         p.index = d->follows[old.index].elems[j].index;
  1092.         insert(p, s);
  1093.       }
  1094.     /* Force rescan to start at the beginning. */
  1095.     i = -1;
  1096.       }
  1097.  
  1098.   free(visited);
  1099. }
  1100.  
  1101. /* Perform bottom-up analysis on the parse tree, computing various functions.
  1102.    Note that at this point, we're pretending constructs like \< are real
  1103.    characters rather than constraints on what can follow them.
  1104.  
  1105.    Nullable:  A node is nullable if it is at the root of a regexp that can
  1106.    match the empty string.
  1107.    *  EMPTY leaves are nullable.
  1108.    * No other leaf is nullable.
  1109.    * A QMARK or STAR node is nullable.
  1110.    * A PLUS node is nullable if its argument is nullable.
  1111.    * A CAT node is nullable if both its arguments are nullable.
  1112.    * An OR node is nullable if either argument is nullable.
  1113.  
  1114.    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  1115.    that could correspond to the first character of a string matching the
  1116.    regexp rooted at the given node.
  1117.    * EMPTY leaves have empty firstpos.
  1118.    * The firstpos of a nonempty leaf is that leaf itself.
  1119.    * The firstpos of a QMARK, STAR, or PLUS node is the firstpos of its
  1120.      argument.
  1121.    * The firstpos of a CAT node is the firstpos of the left argument, union
  1122.      the firstpos of the right if the left argument is nullable.
  1123.    * The firstpos of an OR node is the union of firstpos of each argument.
  1124.  
  1125.    Lastpos:  The lastpos of a node is the set of positions that could
  1126.    correspond to the last character of a string matching the regexp at
  1127.    the given node.
  1128.    * EMPTY leaves have empty lastpos.
  1129.    * The lastpos of a nonempty leaf is that leaf itself.
  1130.    * The lastpos of a QMARK, STAR, or PLUS node is the lastpos of its
  1131.      argument.
  1132.    * The lastpos of a CAT node is the lastpos of its right argument, union
  1133.      the lastpos of the left if the right argument is nullable.
  1134.    * The lastpos of an OR node is the union of the lastpos of each argument.
  1135.  
  1136.    Follow:  The follow of a position is the set of positions that could
  1137.    correspond to the character following a character matching the node in
  1138.    a string matching the regexp.  At this point we consider special symbols
  1139.    that match the empty string in some context to be just normal characters.
  1140.    Later, if we find that a special symbol is in a follow set, we will
  1141.    replace it with the elements of its follow, labeled with an appropriate
  1142.    constraint.
  1143.    * Every node in the firstpos of the argument of a STAR or PLUS node is in
  1144.      the follow of every node in the lastpos.
  1145.    * Every node in the firstpos of the second argument of a CAT node is in
  1146.      the follow of every node in the lastpos of the first argument.
  1147.  
  1148.    Because of the postfix representation of the parse tree, the depth-first
  1149.    analysis is conveniently done by a linear scan with the aid of a stack.
  1150.    Sets are stored as arrays of the elements, obeying a stack-like allocation
  1151.    scheme; the number of elements in each set deeper in the stack can be
  1152.    used to determine the address of a particular set's array. */
  1153. void
  1154. dfaanalyze(d, searchflag)
  1155.      struct dfa *d;
  1156.      int searchflag;
  1157. {
  1158.   int *nullable;        /* Nullable stack. */
  1159.   int *nfirstpos;        /* Element count stack for firstpos sets. */
  1160.   position *firstpos;        /* Array where firstpos elements are stored. */
  1161.   int *nlastpos;        /* Element count stack for lastpos sets. */
  1162.   position *lastpos;        /* Array where lastpos elements are stored. */
  1163.   int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  1164.   position_set tmp;        /* Temporary set for merging sets. */
  1165.   position_set merged;        /* Result of merging sets. */
  1166.   int wants_newline;        /* True if some position wants newline info. */
  1167.   int *o_nullable;
  1168.   int *o_nfirst, *o_nlast;
  1169.   position *o_firstpos, *o_lastpos;
  1170.   int i, j;
  1171.   position *pos;
  1172.  
  1173. #ifdef DEBUG
  1174.   fprintf(stderr, "dfaanalyze:\n");
  1175.   for (i = 0; i < d->tindex; ++i)
  1176.     {
  1177.       fprintf(stderr, " %d:", i);
  1178.       prtok(d->tokens[i]);
  1179.     }
  1180.   putc('\n', stderr);
  1181. #endif
  1182.  
  1183.   d->searchflag = searchflag;
  1184.  
  1185.   MALLOC(nullable, int, d->depth);
  1186.   o_nullable = nullable;
  1187.   MALLOC(nfirstpos, int, d->depth);
  1188.   o_nfirst = nfirstpos;
  1189.   MALLOC(firstpos, position, d->nleaves);
  1190.   o_firstpos = firstpos, firstpos += d->nleaves;
  1191.   MALLOC(nlastpos, int, d->depth);
  1192.   o_nlast = nlastpos;
  1193.   MALLOC(lastpos, position, d->nleaves);
  1194.   o_lastpos = lastpos, lastpos += d->nleaves;
  1195.   MALLOC(nalloc, int, d->tindex);
  1196.   for (i = 0; i < d->tindex; ++i)
  1197.     nalloc[i] = 0;
  1198.   MALLOC(merged.elems, position, d->nleaves);
  1199.  
  1200.   CALLOC(d->follows, position_set, d->tindex);
  1201.  
  1202.   for (i = 0; i < d->tindex; ++i)
  1203. #ifdef DEBUG
  1204.     {                /* Nonsyntactic #ifdef goo... */
  1205. #endif
  1206.     switch (d->tokens[i])
  1207.       {
  1208.       case EMPTY:
  1209.     /* The empty set is nullable. */
  1210.     *nullable++ = 1;
  1211.  
  1212.     /* The firstpos and lastpos of the empty leaf are both empty. */
  1213.     *nfirstpos++ = *nlastpos++ = 0;
  1214.     break;
  1215.  
  1216.       case STAR:
  1217.       case PLUS:
  1218.     /* Every element in the firstpos of the argument is in the follow
  1219.        of every element in the lastpos. */
  1220.     tmp.nelem = nfirstpos[-1];
  1221.     tmp.elems = firstpos;
  1222.     pos = lastpos;
  1223.     for (j = 0; j < nlastpos[-1]; ++j)
  1224.       {
  1225.         merge(&tmp, &d->follows[pos[j].index], &merged);
  1226.         REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1227.                  nalloc[pos[j].index], merged.nelem - 1);
  1228.         copy(&merged, &d->follows[pos[j].index]);
  1229.       }
  1230.  
  1231.       case QMARK:
  1232.     /* A QMARK or STAR node is automatically nullable. */
  1233.     if (d->tokens[i] != PLUS)
  1234.       nullable[-1] = 1;
  1235.     break;
  1236.  
  1237.       case CAT:
  1238.     /* Every element in the firstpos of the second argument is in the
  1239.        follow of every element in the lastpos of the first argument. */
  1240.     tmp.nelem = nfirstpos[-1];
  1241.     tmp.elems = firstpos;
  1242.     pos = lastpos + nlastpos[-1];
  1243.     for (j = 0; j < nlastpos[-2]; ++j)
  1244.       {
  1245.         merge(&tmp, &d->follows[pos[j].index], &merged);
  1246.         REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1247.                  nalloc[pos[j].index], merged.nelem - 1);
  1248.         copy(&merged, &d->follows[pos[j].index]);
  1249.       }
  1250.  
  1251.     /* The firstpos of a CAT node is the firstpos of the first argument,
  1252.        union that of the second argument if the first is nullable. */
  1253.     if (nullable[-2])
  1254.       nfirstpos[-2] += nfirstpos[-1];
  1255.     else
  1256.       firstpos += nfirstpos[-1];
  1257.     --nfirstpos;
  1258.  
  1259.     /* The lastpos of a CAT node is the lastpos of the second argument,
  1260.        union that of the first argument if the second is nullable. */
  1261.     if (nullable[-1])
  1262.       nlastpos[-2] += nlastpos[-1];
  1263.     else
  1264.       {
  1265.         pos = lastpos + nlastpos[-2];
  1266.         for (j = nlastpos[-1] - 1; j >= 0; --j)
  1267.           pos[j] = lastpos[j];
  1268.         lastpos += nlastpos[-2];
  1269.         nlastpos[-2] = nlastpos[-1];
  1270.       }
  1271.     --nlastpos;
  1272.  
  1273.     /* A CAT node is nullable if both arguments are nullable. */
  1274.     nullable[-2] = nullable[-1] && nullable[-2];
  1275.     --nullable;
  1276.     break;
  1277.  
  1278.       case OR:
  1279.       case ORTOP:
  1280.     /* The firstpos is the union of the firstpos of each argument. */
  1281.     nfirstpos[-2] += nfirstpos[-1];
  1282.     --nfirstpos;
  1283.  
  1284.     /* The lastpos is the union of the lastpos of each argument. */
  1285.     nlastpos[-2] += nlastpos[-1];
  1286.     --nlastpos;
  1287.  
  1288.     /* An OR node is nullable if either argument is nullable. */
  1289.     nullable[-2] = nullable[-1] || nullable[-2];
  1290.     --nullable;
  1291.     break;
  1292.  
  1293.       default:
  1294.     /* Anything else is a nonempty position.  (Note that special
  1295.        constructs like \< are treated as nonempty strings here;
  1296.        an "epsilon closure" effectively makes them nullable later.
  1297.        Backreferences have to get a real position so we can detect
  1298.        transitions on them later.  But they are nullable. */
  1299.     *nullable++ = d->tokens[i] == BACKREF;
  1300.  
  1301.     /* This position is in its own firstpos and lastpos. */
  1302.     *nfirstpos++ = *nlastpos++ = 1;
  1303.     --firstpos, --lastpos;
  1304.     firstpos->index = lastpos->index = i;
  1305.     firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
  1306.  
  1307.     /* Allocate the follow set for this position. */
  1308.     nalloc[i] = 1;
  1309.     MALLOC(d->follows[i].elems, position, nalloc[i]);
  1310.     break;
  1311.       }
  1312. #ifdef DEBUG
  1313.     /* ... balance the above nonsyntactic #ifdef goo... */
  1314.       fprintf(stderr, "node %d:", i);
  1315.       prtok(d->tokens[i]);
  1316.       putc('\n', stderr);
  1317.       fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
  1318.       fprintf(stderr, " firstpos:");
  1319.       for (j = nfirstpos[-1] - 1; j >= 0; --j)
  1320.     {
  1321.       fprintf(stderr, " %d:", firstpos[j].index);
  1322.       prtok(d->tokens[firstpos[j].index]);
  1323.     }
  1324.       fprintf(stderr, "\n lastpos:");
  1325.       for (j = nlastpos[-1] - 1; j >= 0; --j)
  1326.     {
  1327.       fprintf(stderr, " %d:", lastpos[j].index);
  1328.       prtok(d->tokens[lastpos[j].index]);
  1329.     }
  1330.       putc('\n', stderr);
  1331.     }
  1332. #endif
  1333.  
  1334.   /* For each follow set that is the follow set of a real position, replace
  1335.      it with its epsilon closure. */
  1336.   for (i = 0; i < d->tindex; ++i)
  1337.     if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
  1338.     || d->tokens[i] >= CSET)
  1339.       {
  1340. #ifdef DEBUG
  1341.     fprintf(stderr, "follows(%d:", i);
  1342.     prtok(d->tokens[i]);
  1343.     fprintf(stderr, "):");
  1344.     for (j = d->follows[i].nelem - 1; j >= 0; --j)
  1345.       {
  1346.         fprintf(stderr, " %d:", d->follows[i].elems[j].index);
  1347.         prtok(d->tokens[d->follows[i].elems[j].index]);
  1348.       }
  1349.     putc('\n', stderr);
  1350. #endif
  1351.     copy(&d->follows[i], &merged);
  1352.     epsclosure(&merged, d);
  1353.     if (d->follows[i].nelem < merged.nelem)
  1354.       REALLOC(d->follows[i].elems, position, merged.nelem);
  1355.     copy(&merged, &d->follows[i]);
  1356.       }
  1357.  
  1358.   /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1359.      be the set of positions of state 0. */
  1360.   merged.nelem = 0;
  1361.   for (i = 0; i < nfirstpos[-1]; ++i)
  1362.     insert(firstpos[i], &merged);
  1363.   epsclosure(&merged, d);
  1364.  
  1365.   /* Check if any of the positions of state 0 will want newline context. */
  1366.   wants_newline = 0;
  1367.   for (i = 0; i < merged.nelem; ++i)
  1368.     if (PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1369.       wants_newline = 1;
  1370.  
  1371.   /* Build the initial state. */
  1372.   d->salloc = 1;
  1373.   d->sindex = 0;
  1374.   MALLOC(d->states, dfa_state, d->salloc);
  1375.   state_index(d, &merged, wants_newline, 0);
  1376.  
  1377.   free(o_nullable);
  1378.   free(o_nfirst);
  1379.   free(o_firstpos);
  1380.   free(o_nlast);
  1381.   free(o_lastpos);
  1382.   free(nalloc);
  1383.   free(merged.elems);
  1384. }
  1385.  
  1386. /* Find, for each character, the transition out of state s of d, and store
  1387.    it in the appropriate slot of trans.
  1388.  
  1389.    We divide the positions of s into groups (positions can appear in more
  1390.    than one group).  Each group is labeled with a set of characters that
  1391.    every position in the group matches (taking into account, if necessary,
  1392.    preceding context information of s).  For each group, find the union
  1393.    of the its elements' follows.  This set is the set of positions of the
  1394.    new state.  For each character in the group's label, set the transition
  1395.    on this character to be to a state corresponding to the set's positions,
  1396.    and its associated backward context information, if necessary.
  1397.  
  1398.    If we are building a searching matcher, we include the positions of state
  1399.    0 in every state.
  1400.  
  1401.    The collection of groups is constructed by building an equivalence-class
  1402.    partition of the positions of s.
  1403.  
  1404.    For each position, find the set of characters C that it matches.  Eliminate
  1405.    any characters from C that fail on grounds of backward context.
  1406.  
  1407.    Search through the groups, looking for a group whose label L has nonempty
  1408.    intersection with C.  If L - C is nonempty, create a new group labeled
  1409.    L - C and having the same positions as the current group, and set L to
  1410.    the intersection of L and C.  Insert the position in this group, set
  1411.    C = C - L, and resume scanning.
  1412.  
  1413.    If after comparing with every group there are characters remaining in C,
  1414.    create a new group labeled with the characters of C and insert this
  1415.    position in that group. */
  1416. void
  1417. dfastate(s, d, trans)
  1418.      int s;
  1419.      struct dfa *d;
  1420.      int trans[];
  1421. {
  1422.   position_set grps[NOTCHAR];    /* As many as will ever be needed. */
  1423.   charclass labels[NOTCHAR];    /* Labels corresponding to the groups. */
  1424.   int ngrps = 0;        /* Number of groups actually used. */
  1425.   position pos;            /* Current position being considered. */
  1426.   charclass matches;        /* Set of matching characters. */
  1427.   int matchesf;            /* True if matches is nonempty. */
  1428.   charclass intersect;        /* Intersection with some label set. */
  1429.   int intersectf;        /* True if intersect is nonempty. */
  1430.   charclass leftovers;        /* Stuff in the label that didn't match. */
  1431.   int leftoversf;        /* True if leftovers is nonempty. */
  1432.   static charclass letters;    /* Set of characters considered letters. */
  1433.   static charclass newline;    /* Set of characters that aren't newline. */
  1434.   position_set follows;        /* Union of the follows of some group. */
  1435.   position_set tmp;        /* Temporary space for merging sets. */
  1436.   int state;            /* New state. */
  1437.   int wants_newline;        /* New state wants to know newline context. */
  1438.   int state_newline;        /* New state on a newline transition. */
  1439.   int wants_letter;        /* New state wants to know letter context. */
  1440.   int state_letter;        /* New state on a letter transition. */
  1441.   static initialized;        /* Flag for static initialization. */
  1442.   int i, j, k;
  1443.  
  1444.   /* Initialize the set of letters, if necessary. */
  1445.   if (! initialized)
  1446.     {
  1447.       initialized = 1;
  1448.       for (i = 0; i < NOTCHAR; ++i)
  1449.     if (ISALNUM(i))
  1450.       setbit(i, letters);
  1451.       setbit('\n', newline);
  1452.     }
  1453.  
  1454.   zeroset(matches);
  1455.  
  1456.   for (i = 0; i < d->states[s].elems.nelem; ++i)
  1457.     {
  1458.       pos = d->states[s].elems.elems[i];
  1459.       if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR)
  1460.     setbit(d->tokens[pos.index], matches);
  1461.       else if (d->tokens[pos.index] >= CSET)
  1462.     copyset(d->charclasses[d->tokens[pos.index] - CSET], matches);
  1463.       else
  1464.     continue;
  1465.  
  1466.       /* Some characters may need to be eliminated from matches because
  1467.      they fail in the current context. */
  1468.       if (pos.constraint != 0xFF)
  1469.     {
  1470.       if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1471.                      d->states[s].newline, 1))
  1472.         clrbit('\n', matches);
  1473.       if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1474.                      d->states[s].newline, 0))
  1475.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1476.           matches[j] &= newline[j];
  1477.       if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1478.                     d->states[s].letter, 1))
  1479.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1480.           matches[j] &= ~letters[j];
  1481.       if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1482.                     d->states[s].letter, 0))
  1483.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1484.           matches[j] &= letters[j];
  1485.  
  1486.       /* If there are no characters left, there's no point in going on. */
  1487.       for (j = 0; j < CHARCLASS_INTS && !matches[j]; ++j)
  1488.         ;
  1489.       if (j == CHARCLASS_INTS)
  1490.         continue;
  1491.     }
  1492.  
  1493.       for (j = 0; j < ngrps; ++j)
  1494.     {
  1495.       /* If matches contains a single character only, and the current
  1496.          group's label doesn't contain that character, go on to the
  1497.          next group. */
  1498.       if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR
  1499.           && !tstbit(d->tokens[pos.index], labels[j]))
  1500.         continue;
  1501.  
  1502.       /* Check if this group's label has a nonempty intersection with
  1503.          matches. */
  1504.       intersectf = 0;
  1505.       for (k = 0; k < CHARCLASS_INTS; ++k)
  1506.         (intersect[k] = matches[k] & labels[j][k]) ? intersectf = 1 : 0;
  1507.       if (! intersectf)
  1508.         continue;
  1509.  
  1510.       /* It does; now find the set differences both ways. */
  1511.       leftoversf = matchesf = 0;
  1512.       for (k = 0; k < CHARCLASS_INTS; ++k)
  1513.         {
  1514.           /* Even an optimizing compiler can't know this for sure. */
  1515.           int match = matches[k], label = labels[j][k];
  1516.  
  1517.           (leftovers[k] = ~match & label) ? leftoversf = 1 : 0;
  1518.           (matches[k] = match & ~label) ? matchesf = 1 : 0;
  1519.         }
  1520.  
  1521.       /* If there were leftovers, create a new group labeled with them. */
  1522.       if (leftoversf)
  1523.         {
  1524.           copyset(leftovers, labels[ngrps]);
  1525.           copyset(intersect, labels[j]);
  1526.           MALLOC(grps[ngrps].elems, position, d->nleaves);
  1527.           copy(&grps[j], &grps[ngrps]);
  1528.           ++ngrps;
  1529.         }
  1530.  
  1531.       /* Put the position in the current group.  Note that there is no
  1532.          reason to call insert() here. */
  1533.       grps[j].elems[grps[j].nelem++] = pos;
  1534.  
  1535.       /* If every character matching the current position has been
  1536.          accounted for, we're done. */
  1537.       if (! matchesf)
  1538.         break;
  1539.     }
  1540.  
  1541.       /* If we've passed the last group, and there are still characters
  1542.      unaccounted for, then we'll have to create a new group. */
  1543.       if (j == ngrps)
  1544.     {
  1545.       copyset(matches, labels[ngrps]);
  1546.       zeroset(matches);
  1547.       MALLOC(grps[ngrps].elems, position, d->nleaves);
  1548.       grps[ngrps].nelem = 1;
  1549.       grps[ngrps].elems[0] = pos;
  1550.       ++ngrps;
  1551.     }
  1552.     }
  1553.  
  1554.   MALLOC(follows.elems, position, d->nleaves);
  1555.   MALLOC(tmp.elems, position, d->nleaves);
  1556.  
  1557.   /* If we are a searching matcher, the default transition is to a state
  1558.      containing the positions of state 0, otherwise the default transition
  1559.      is to fail miserably. */
  1560.   if (d->searchflag)
  1561.     {
  1562.       wants_newline = 0;
  1563.       wants_letter = 0;
  1564.       for (i = 0; i < d->states[0].elems.nelem; ++i)
  1565.     {
  1566.       if (PREV_NEWLINE_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1567.         wants_newline = 1;
  1568.       if (PREV_LETTER_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1569.         wants_letter = 1;
  1570.     }
  1571.       copy(&d->states[0].elems, &follows);
  1572.       state = state_index(d, &follows, 0, 0);
  1573.       if (wants_newline)
  1574.     state_newline = state_index(d, &follows, 1, 0);
  1575.       else
  1576.     state_newline = state;
  1577.       if (wants_letter)
  1578.     state_letter = state_index(d, &follows, 0, 1);
  1579.       else
  1580.     state_letter = state;
  1581.       for (i = 0; i < NOTCHAR; ++i)
  1582.     if (i == '\n')
  1583.       trans[i] = state_newline;
  1584.     else if (ISALNUM(i))
  1585.       trans[i] = state_letter;
  1586.     else
  1587.       trans[i] = state;
  1588.     }
  1589.   else
  1590.     for (i = 0; i < NOTCHAR; ++i)
  1591.       trans[i] = -1;
  1592.  
  1593.   for (i = 0; i < ngrps; ++i)
  1594.     {
  1595.       follows.nelem = 0;
  1596.  
  1597.       /* Find the union of the follows of the positions of the group.
  1598.      This is a hideously inefficient loop.  Fix it someday. */
  1599.       for (j = 0; j < grps[i].nelem; ++j)
  1600.     for (k = 0; k < d->follows[grps[i].elems[j].index].nelem; ++k)
  1601.       insert(d->follows[grps[i].elems[j].index].elems[k], &follows);
  1602.  
  1603.       /* If we are building a searching matcher, throw in the positions
  1604.      of state 0 as well. */
  1605.       if (d->searchflag)
  1606.     for (j = 0; j < d->states[0].elems.nelem; ++j)
  1607.       insert(d->states[0].elems.elems[j], &follows);
  1608.  
  1609.       /* Find out if the new state will want any context information. */
  1610.       wants_newline = 0;
  1611.       if (tstbit('\n', labels[i]))
  1612.     for (j = 0; j < follows.nelem; ++j)
  1613.       if (PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1614.         wants_newline = 1;
  1615.  
  1616.       wants_letter = 0;
  1617.       for (j = 0; j < CHARCLASS_INTS; ++j)
  1618.     if (labels[i][j] & letters[j])
  1619.       break;
  1620.       if (j < CHARCLASS_INTS)
  1621.     for (j = 0; j < follows.nelem; ++j)
  1622.       if (PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1623.         wants_letter = 1;
  1624.  
  1625.       /* Find the state(s) corresponding to the union of the follows. */
  1626.       state = state_index(d, &follows, 0, 0);
  1627.       if (wants_newline)
  1628.     state_newline = state_index(d, &follows, 1, 0);
  1629.       else
  1630.     state_newline = state;
  1631.       if (wants_letter)
  1632.     state_letter = state_index(d, &follows, 0, 1);
  1633.       else
  1634.     state_letter = state;
  1635.  
  1636.       /* Set the transitions for each character in the current label. */
  1637.       for (j = 0; j < CHARCLASS_INTS; ++j)
  1638.     for (k = 0; k < INTBITS; ++k)
  1639.       if (labels[i][j] & 1 << k)
  1640.         {
  1641.           int c = j * INTBITS + k;
  1642.  
  1643.           if (c == '\n')
  1644.         trans[c] = state_newline;
  1645.           else if (ISALNUM(c))
  1646.         trans[c] = state_letter;
  1647.           else if (c < NOTCHAR)
  1648.         trans[c] = state;
  1649.         }
  1650.     }
  1651.  
  1652.   for (i = 0; i < ngrps; ++i)
  1653.     free(grps[i].elems);
  1654.   free(follows.elems);
  1655.   free(tmp.elems);
  1656. }
  1657.  
  1658. /* Some routines for manipulating a compiled dfa's transition tables.
  1659.    Each state may or may not have a transition table; if it does, and it
  1660.    is a non-accepting state, then d->trans[state] points to its table.
  1661.    If it is an accepting state then d->fails[state] points to its table.
  1662.    If it has no table at all, then d->trans[state] is NULL.
  1663.    TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1664.  
  1665. static void
  1666. build_state(
  1667.      int s,
  1668.      struct dfa *d)
  1669. {
  1670.   int *trans;            /* The new transition table. */
  1671.   int i;
  1672.  
  1673.   /* Set an upper limit on the number of transition tables that will ever
  1674.      exist at once.  1024 is arbitrary.  The idea is that the frequently
  1675.      used transition tables will be quickly rebuilt, whereas the ones that
  1676.      were only needed once or twice will be cleared away. */
  1677.   if (d->trcount >= 1024)
  1678.     {
  1679.       for (i = 0; i < d->tralloc; ++i)
  1680.     if (d->trans[i])
  1681.       {
  1682.         free((ptr_t) d->trans[i]);
  1683.         d->trans[i] = NULL;
  1684.       }
  1685.     else if (d->fails[i])
  1686.       {
  1687.         free((ptr_t) d->fails[i]);
  1688.         d->fails[i] = NULL;
  1689.       }
  1690.       d->trcount = 0;
  1691.     }
  1692.  
  1693.   ++d->trcount;
  1694.  
  1695.   /* Set up the success bits for this state. */
  1696.   d->success[s] = 0;
  1697.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 1, d->states[s].letter, 0,
  1698.       s, *d))
  1699.     d->success[s] |= 4;
  1700.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 1,
  1701.       s, *d))
  1702.     d->success[s] |= 2;
  1703.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 0,
  1704.       s, *d))
  1705.     d->success[s] |= 1;
  1706.  
  1707.   MALLOC(trans, int, NOTCHAR);
  1708.   dfastate(s, d, trans);
  1709.  
  1710.   /* Now go through the new transition table, and make sure that the trans
  1711.      and fail arrays are allocated large enough to hold a pointer for the
  1712.      largest state mentioned in the table. */
  1713.   for (i = 0; i < NOTCHAR; ++i)
  1714.     if (trans[i] >= d->tralloc)
  1715.       {
  1716.     int oldalloc = d->tralloc;
  1717.  
  1718.     while (trans[i] >= d->tralloc)
  1719.       d->tralloc *= 2;
  1720.     REALLOC(d->realtrans, int *, d->tralloc + 1);
  1721.     d->trans = d->realtrans + 1;
  1722.     REALLOC(d->fails, int *, d->tralloc);
  1723.     REALLOC(d->success, int, d->tralloc);
  1724.     REALLOC(d->newlines, int, d->tralloc);
  1725.     while (oldalloc < d->tralloc)
  1726.       {
  1727.         d->trans[oldalloc] = NULL;
  1728.         d->fails[oldalloc++] = NULL;
  1729.       }
  1730.       }
  1731.  
  1732.   /* Keep the newline transition in a special place so we can use it as
  1733.      a sentinel. */
  1734.   d->newlines[s] = trans['\n'];
  1735.   trans['\n'] = -1;
  1736.  
  1737.   if (ACCEPTING(s, *d))
  1738.     d->fails[s] = trans;
  1739.   else
  1740.     d->trans[s] = trans;
  1741. }
  1742.  
  1743. static void
  1744. build_state_zero(
  1745.      struct dfa *d)
  1746. {
  1747.   d->tralloc = 1;
  1748.   d->trcount = 0;
  1749.   CALLOC(d->realtrans, int *, d->tralloc + 1);
  1750.   d->trans = d->realtrans + 1;
  1751.   CALLOC(d->fails, int *, d->tralloc);
  1752.   MALLOC(d->success, int, d->tralloc);
  1753.   MALLOC(d->newlines, int, d->tralloc);
  1754.   build_state(0, d);
  1755. }
  1756.  
  1757. /* Search through a buffer looking for a match to the given struct dfa.
  1758.    Find the first occurrence of a string matching the regexp in the buffer,
  1759.    and the shortest possible version thereof.  Return a pointer to the first
  1760.    character after the match, or NULL if none is found.  Begin points to
  1761.    the beginning of the buffer, and end points to the first character after
  1762.    its end.  We store a newline in *end to act as a sentinel, so end had
  1763.    better point somewhere valid.  Newline is a flag indicating whether to
  1764.    allow newlines to be in the matching string.  If count is non-
  1765.    NULL it points to a place we're supposed to increment every time we
  1766.    see a newline.  Finally, if backref is non-NULL it points to a place
  1767.    where we're supposed to store a 1 if backreferencing happened and the
  1768.    match needs to be verified by a backtracking matcher.  Otherwise
  1769.    we store a 0 in *backref. */
  1770. char *
  1771. dfaexec(d, begin, end, newline, count, backref)
  1772.      struct dfa *d;
  1773.      char *begin;
  1774.      char *end;
  1775.      int newline;
  1776.      int *count;
  1777.      int *backref;
  1778. {
  1779.   register s, s1, tmp;        /* Current state. */
  1780.   register unsigned char *p;    /* Current input character. */
  1781.   register **trans, *t;        /* Copy of d->trans so it can be optimized
  1782.                    into a register. */
  1783.   static sbit[NOTCHAR];    /* Table for anding with d->success. */
  1784.   static sbit_init;
  1785.  
  1786.   if (! sbit_init)
  1787.     {
  1788.       int i;
  1789.  
  1790.       sbit_init = 1;
  1791.       for (i = 0; i < NOTCHAR; ++i)
  1792.     if (i == '\n')
  1793.       sbit[i] = 4;
  1794.     else if (ISALNUM(i))
  1795.       sbit[i] = 2;
  1796.     else
  1797.       sbit[i] = 1;
  1798.     }
  1799.  
  1800.   if (! d->tralloc)
  1801.     build_state_zero(d);
  1802.  
  1803.   s = s1 = 0;
  1804.   p = (unsigned char *) begin;
  1805.   trans = d->trans;
  1806.   *end = '\n';
  1807.  
  1808.   for (;;)
  1809.     {
  1810.       /* The dreaded inner loop. */
  1811.       if ((t = trans[s]) != 0)
  1812.     do
  1813.       {
  1814.         s1 = t[*p++];
  1815.         if (! (t = trans[s1]))
  1816.           goto last_was_s;
  1817.         s = t[*p++];
  1818.       }
  1819.         while ((t = trans[s]) != 0);
  1820.       goto last_was_s1;
  1821.     last_was_s:
  1822.       tmp = s, s = s1, s1 = tmp;
  1823.     last_was_s1:
  1824.  
  1825.       if (s >= 0 && p <= (unsigned char *) end && d->fails[s])
  1826.     {
  1827.       if (d->success[s] & sbit[*p])
  1828.         {
  1829.           if (backref)
  1830.         if (d->states[s].backref)
  1831.           *backref = 1;
  1832.         else
  1833.           *backref = 0;
  1834.           return (char *) p;
  1835.         }
  1836.  
  1837.       s1 = s;
  1838.       s = d->fails[s][*p++];
  1839.       continue;
  1840.     }
  1841.  
  1842.       /* If the previous character was a newline, count it. */
  1843.       if (count && (char *) p <= end && p[-1] == '\n')
  1844.     ++*count;
  1845.  
  1846.       /* Check if we've run off the end of the buffer. */
  1847.       if ((char *) p > end)
  1848.     return NULL;
  1849.  
  1850.       if (s >= 0)
  1851.     {
  1852.       build_state(s, d);
  1853.       trans = d->trans;
  1854.       continue;
  1855.     }
  1856.  
  1857.       if (p[-1] == '\n' && newline)
  1858.     {
  1859.       s = d->newlines[s1];
  1860.       continue;
  1861.     }
  1862.  
  1863.       s = 0;
  1864.     }
  1865. }
  1866.  
  1867. /* Initialize the components of a dfa that the other routines don't
  1868.    initialize for themselves. */
  1869. void
  1870. dfainit(d)
  1871.      struct dfa *d;
  1872. {
  1873.   d->calloc = 1;
  1874.   MALLOC(d->charclasses, charclass, d->calloc);
  1875.   d->cindex = 0;
  1876.  
  1877.   d->talloc = 1;
  1878.   MALLOC(d->tokens, token, d->talloc);
  1879.   d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  1880.  
  1881.   d->searchflag = 0;
  1882.   d->tralloc = 0;
  1883.  
  1884.   d->musts = 0;
  1885. }
  1886.  
  1887. /* Parse and analyze a single string of the given length. */
  1888. void
  1889. dfacomp(s, len, d, searchflag)
  1890.      char *s;
  1891.      size_t len;
  1892.      struct dfa *d;
  1893.      int searchflag;
  1894. {
  1895.   if (case_fold)    /* dummy folding in service of dfamust() */
  1896.     {
  1897.       char *copy;
  1898.       int i;
  1899.  
  1900.       copy = malloc(len);
  1901.       if (!copy)
  1902.     dfaerror("out of memory");
  1903.       
  1904.       /* This is a kludge. */
  1905.       case_fold = 0;
  1906.       for (i = 0; i < len; ++i)
  1907.     if (ISUPPER(s[i]))
  1908.       copy[i] = tolower(s[i]);
  1909.     else
  1910.       copy[i] = s[i];
  1911.  
  1912.       dfainit(d);
  1913.       dfaparse(copy, len, d);
  1914.       free(copy);
  1915.       dfamust(d);
  1916.       d->cindex = d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  1917.       case_fold = 1;
  1918.       dfaparse(s, len, d);
  1919.       dfaanalyze(d, searchflag);
  1920.     }
  1921.   else
  1922.     {
  1923.         dfainit(d);
  1924.         dfaparse(s, len, d);
  1925.     dfamust(d);
  1926.         dfaanalyze(d, searchflag);
  1927.     }
  1928. }
  1929.  
  1930. /* Free the storage held by the components of a dfa. */
  1931. void
  1932. dfafree(d)
  1933.      struct dfa *d;
  1934. {
  1935.   int i;
  1936.   struct dfamust *dm, *ndm;
  1937.  
  1938.   free((ptr_t) d->charclasses);
  1939.   free((ptr_t) d->tokens);
  1940.   for (i = 0; i < d->sindex; ++i)
  1941.     free((ptr_t) d->states[i].elems.elems);
  1942.   free((ptr_t) d->states);
  1943.   for (i = 0; i < d->tindex; ++i)
  1944.     if (d->follows[i].elems)
  1945.       free((ptr_t) d->follows[i].elems);
  1946.   free((ptr_t) d->follows);
  1947.   for (i = 0; i < d->tralloc; ++i)
  1948.     if (d->trans[i])
  1949.       free((ptr_t) d->trans[i]);
  1950.     else if (d->fails[i])
  1951.       free((ptr_t) d->fails[i]);
  1952.   free((ptr_t) d->realtrans);
  1953.   free((ptr_t) d->fails);
  1954.   free((ptr_t) d->newlines);
  1955.   for (dm = d->musts; dm; dm = ndm)
  1956.     {
  1957.       ndm = dm->next;
  1958.       free(dm->must);
  1959.       free((ptr_t) dm);
  1960.     }
  1961. }
  1962.  
  1963. /* Having found the postfix representation of the regular expression,
  1964.    try to find a long sequence of characters that must appear in any line
  1965.    containing the r.e.
  1966.    Finding a "longest" sequence is beyond the scope here;
  1967.    we take an easy way out and hope for the best.
  1968.    (Take "(ab|a)b"--please.)
  1969.  
  1970.    We do a bottom-up calculation of sequences of characters that must appear
  1971.    in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  1972.    representation:
  1973.     sequences that must appear at the left of the match ("left")
  1974.     sequences that must appear at the right of the match ("right")
  1975.     lists of sequences that must appear somewhere in the match ("in")
  1976.     sequences that must constitute the match ("is")
  1977.  
  1978.    When we get to the root of the tree, we use one of the longest of its
  1979.    calculated "in" sequences as our answer.  The sequence we find is returned in
  1980.    d->must (where "d" is the single argument passed to "dfamust");
  1981.    the length of the sequence is returned in d->mustn.
  1982.  
  1983.    The sequences calculated for the various types of node (in pseudo ANSI c)
  1984.    are shown below.  "p" is the operand of unary operators (and the left-hand
  1985.    operand of binary operators); "q" is the right-hand operand of binary
  1986.    operators.
  1987.  
  1988.    "ZERO" means "a zero-length sequence" below.
  1989.  
  1990.     Type    left        right        is        in
  1991.     ----    ----        -----        --        --
  1992.     char c    # c        # c        # c        # c
  1993.     
  1994.     CSET    ZERO        ZERO        ZERO        ZERO
  1995.     
  1996.     STAR    ZERO        ZERO        ZERO        ZERO
  1997.  
  1998.     QMARK    ZERO        ZERO        ZERO        ZERO
  1999.  
  2000.     PLUS    p->left        p->right    ZERO        p->in
  2001.  
  2002.     CAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    p->in plus
  2003.         p->left :    q->right :    q->is!=ZERO) ?    q->in plus
  2004.         p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  2005.                         ZERO
  2006.                     
  2007.     OR    longest common    longest common    (do p->is and    substrings common to
  2008.         leading        trailing    q->is have same    p->in and q->in
  2009.         (sub)sequence    (sub)sequence    length and    
  2010.         of p->left    of p->right    content) ?    
  2011.         and q->left    and q->right    p->is : NULL    
  2012.  
  2013.    If there's anything else we recognize in the tree, all four sequences get set
  2014.    to zero-length sequences.  If there's something we don't recognize in the tree,
  2015.    we just return a zero-length sequence.
  2016.  
  2017.    Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  2018.    'aaa')?
  2019.  
  2020.    And. . .is it here or someplace that we might ponder "optimizations" such as
  2021.     egrep 'psi|epsilon'    ->    egrep 'psi'
  2022.     egrep 'pepsi|epsilon'    ->    egrep 'epsi'
  2023.                     (Yes, we now find "epsi" as a "string
  2024.                     that must occur", but we might also
  2025.                     simplify the *entire* r.e. being sought)
  2026.     grep '[c]'        ->    grep 'c'
  2027.     grep '(ab|a)b'        ->    grep 'ab'
  2028.     grep 'ab*'        ->    grep 'a'
  2029.     grep 'a*b'        ->    grep 'b'
  2030.  
  2031.    There are several issues:
  2032.  
  2033.    Is optimization easy (enough)?
  2034.  
  2035.    Does optimization actually accomplish anything,
  2036.    or is the automaton you get from "psi|epsilon" (for example)
  2037.    the same as the one you get from "psi" (for example)?
  2038.   
  2039.    Are optimizable r.e.'s likely to be used in real-life situations
  2040.    (something like 'ab*' is probably unlikely; something like is
  2041.    'psi|epsilon' is likelier)? */
  2042.  
  2043. static char *
  2044. icatalloc(
  2045.      char *old,
  2046.      char *new)
  2047. {
  2048.   char *result;
  2049.   int oldsize, newsize;
  2050.  
  2051.   newsize = (new == NULL) ? 0 : strlen(new);
  2052.   if (old == NULL)
  2053.     oldsize = 0;
  2054.   else if (newsize == 0)
  2055.     return old;
  2056.   else    oldsize = strlen(old);
  2057.   if (old == NULL)
  2058.     result = (char *) malloc(newsize + 1);
  2059.   else
  2060.     result = (char *) realloc((void *) old, oldsize + newsize + 1);
  2061.   if (result != NULL && new != NULL)
  2062.     (void) strcpy(result + oldsize, new);
  2063.   return result;
  2064. }
  2065.  
  2066. static char *
  2067. icpyalloc(
  2068.      char *string)
  2069. {
  2070.   return icatalloc((char *) NULL, string);
  2071. }
  2072.  
  2073. static char *
  2074. istrstr(
  2075.      char *lookin,
  2076.      char *lookfor)
  2077. {
  2078.   char *cp;
  2079.   int len;
  2080.  
  2081.   len = strlen(lookfor);
  2082.   for (cp = lookin; *cp != '\0'; ++cp)
  2083.     if (strncmp(cp, lookfor, len) == 0)
  2084.       return cp;
  2085.   return NULL;
  2086. }
  2087.  
  2088. static void
  2089. ifree(
  2090.      char *cp)
  2091. {
  2092.   if (cp != NULL)
  2093.     free(cp);
  2094. }
  2095.  
  2096. static void
  2097. freelist(
  2098.      char **cpp)
  2099. {
  2100.   int i;
  2101.  
  2102.   if (cpp == NULL)
  2103.     return;
  2104.   for (i = 0; cpp[i] != NULL; ++i)
  2105.     {
  2106.       free(cpp[i]);
  2107.       cpp[i] = NULL;
  2108.     }
  2109. }
  2110.  
  2111. static char **
  2112. enlist(
  2113.      char **cpp,
  2114.      char *new,
  2115.      int len)
  2116. {
  2117.   int i, j;
  2118.  
  2119.   if (cpp == NULL)
  2120.     return NULL;
  2121.   if ((new = icpyalloc(new)) == NULL)
  2122.     {
  2123.       freelist(cpp);
  2124.       return NULL;
  2125.     }
  2126.   new[len] = '\0';
  2127.   /* Is there already something in the list that's new (or longer)? */
  2128.   for (i = 0; cpp[i] != NULL; ++i)
  2129.     if (istrstr(cpp[i], new) != NULL)
  2130.       {
  2131.     free(new);
  2132.     return cpp;
  2133.       }
  2134.   /* Eliminate any obsoleted strings. */
  2135.   j = 0;
  2136.   while (cpp[j] != NULL)
  2137.     if (istrstr(new, cpp[j]) == NULL)
  2138.       ++j;
  2139.     else
  2140.       {
  2141.     free(cpp[j]);
  2142.     if (--i == j)
  2143.       break;
  2144.     cpp[j] = cpp[i];
  2145.     cpp[i] = NULL;
  2146.       }
  2147.   /* Add the new string. */
  2148.   cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  2149.   if (cpp == NULL)
  2150.     return NULL;
  2151.   cpp[i] = new;
  2152.   cpp[i + 1] = NULL;
  2153.   return cpp;
  2154. }
  2155.  
  2156. /* Given pointers to two strings, return a pointer to an allocated
  2157.    list of their distinct common substrings. Return NULL if something
  2158.    seems wild. */
  2159. static char **
  2160. comsubs(
  2161.      char *left,
  2162.      char *right)
  2163. {
  2164.   char **cpp;
  2165.   char *lcp;
  2166.   char *rcp;
  2167.   int i, len;
  2168.  
  2169.   if (left == NULL || right == NULL)
  2170.     return NULL;
  2171.   cpp = (char **) malloc(sizeof *cpp);
  2172.   if (cpp == NULL)
  2173.     return NULL;
  2174.   cpp[0] = NULL;
  2175.   for (lcp = left; *lcp != '\0'; ++lcp)
  2176.     {
  2177.       len = 0;
  2178.       rcp = index(right, *lcp);
  2179.       while (rcp != NULL)
  2180.     {
  2181.       for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  2182.         ;
  2183.       if (i > len)
  2184.         len = i;
  2185.       rcp = index(rcp + 1, *lcp);
  2186.     }
  2187.       if (len == 0)
  2188.     continue;
  2189.       if ((cpp = enlist(cpp, lcp, len)) == NULL)
  2190.     break;
  2191.     }
  2192.   return cpp;
  2193. }
  2194.  
  2195. static char **
  2196. addlists(
  2197. char **old,
  2198. char **new)
  2199. {
  2200.   int i;
  2201.  
  2202.   if (old == NULL || new == NULL)
  2203.     return NULL;
  2204.   for (i = 0; new[i] != NULL; ++i)
  2205.     {
  2206.       old = enlist(old, new[i], strlen(new[i]));
  2207.       if (old == NULL)
  2208.     break;
  2209.     }
  2210.   return old;
  2211. }
  2212.  
  2213. /* Given two lists of substrings, return a new list giving substrings
  2214.    common to both. */
  2215. static char **
  2216. inboth(
  2217.      char **left,
  2218.      char **right)
  2219. {
  2220.   char **both;
  2221.   char **temp;
  2222.   int lnum, rnum;
  2223.  
  2224.   if (left == NULL || right == NULL)
  2225.     return NULL;
  2226.   both = (char **) malloc(sizeof *both);
  2227.   if (both == NULL)
  2228.     return NULL;
  2229.   both[0] = NULL;
  2230.   for (lnum = 0; left[lnum] != NULL; ++lnum)
  2231.     {
  2232.       for (rnum = 0; right[rnum] != NULL; ++rnum)
  2233.     {
  2234.       temp = comsubs(left[lnum], right[rnum]);
  2235.       if (temp == NULL)
  2236.         {
  2237.           freelist(both);
  2238.           return NULL;
  2239.         }
  2240.       both = addlists(both, temp);
  2241.       freelist(temp);
  2242.       if (both == NULL)
  2243.         return NULL;
  2244.     }
  2245.     }
  2246.   return both;
  2247. }
  2248.  
  2249. typedef struct
  2250. {
  2251.   char **in;
  2252.   char *left;
  2253.   char *right;
  2254.   char *is;
  2255. } must;
  2256.  
  2257. static void
  2258. resetmust(
  2259. must *mp)
  2260. {
  2261.   mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2262.   freelist(mp->in);
  2263. }
  2264.  
  2265. static void
  2266. dfamust(
  2267. struct dfa *dfa)
  2268. {
  2269.   must *musts;
  2270.   must *mp;
  2271.   char *result;
  2272.   int ri;
  2273.   int i;
  2274.   int exact;
  2275.   token t;
  2276.   static must must0;
  2277.   struct dfamust *dm;
  2278.  
  2279.   result = "";
  2280.   exact = 0;
  2281.   musts = (must *) malloc((dfa->tindex + 1) * sizeof *musts);
  2282.   if (musts == NULL)
  2283.     return;
  2284.   mp = musts;
  2285.   for (i = 0; i <= dfa->tindex; ++i)
  2286.     mp[i] = must0;
  2287.   for (i = 0; i <= dfa->tindex; ++i)
  2288.     {
  2289.       mp[i].in = (char **) malloc(sizeof *mp[i].in);
  2290.       mp[i].left = malloc(2);
  2291.       mp[i].right = malloc(2);
  2292.       mp[i].is = malloc(2);
  2293.       if (mp[i].in == NULL || mp[i].left == NULL ||
  2294.       mp[i].right == NULL || mp[i].is == NULL)
  2295.     goto done;
  2296.       mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  2297.       mp[i].in[0] = NULL;
  2298.     }
  2299. #ifdef DEBUG
  2300.   fprintf(stderr, "dfamust:\n");
  2301.   for (i = 0; i < dfa->tindex; ++i)
  2302.     {
  2303.       fprintf(stderr, " %d:", i);
  2304.       prtok(dfa->tokens[i]);
  2305.     }
  2306.   putc('\n', stderr);
  2307. #endif
  2308.   for (ri = 0; ri < dfa->tindex; ++ri)
  2309.     {
  2310.       switch (t = dfa->tokens[ri])
  2311.     {
  2312.     case LPAREN:
  2313.     case RPAREN:
  2314.       goto done;        /* "cannot happen" */
  2315.     case EMPTY:
  2316.     case BEGLINE:
  2317.     case ENDLINE:
  2318.     case BEGWORD:
  2319.     case ENDWORD:
  2320.     case LIMWORD:
  2321.     case NOTLIMWORD:
  2322.     case BACKREF:
  2323.       resetmust(mp);
  2324.       break;
  2325.     case STAR:
  2326.     case QMARK:
  2327.       if (mp <= musts)
  2328.         goto done;        /* "cannot happen" */
  2329.       --mp;
  2330.       resetmust(mp);
  2331.       break;
  2332.     case OR:
  2333.     case ORTOP:
  2334.       if (mp < &musts[2])
  2335.         goto done;        /* "cannot happen" */
  2336.       {
  2337.         char **new;
  2338.         must *lmp;
  2339.         must *rmp;
  2340.         int j, ln, rn, n;
  2341.  
  2342.         rmp = --mp;
  2343.         lmp = --mp;
  2344.         /* Guaranteed to be.  Unlikely, but. . . */
  2345.         if (strcmp(lmp->is, rmp->is) != 0)
  2346.           lmp->is[0] = '\0';
  2347.         /* Left side--easy */
  2348.         i = 0;
  2349.         while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
  2350.           ++i;
  2351.         lmp->left[i] = '\0';
  2352.         /* Right side */
  2353.         ln = strlen(lmp->right);
  2354.         rn = strlen(rmp->right);
  2355.         n = ln;
  2356.         if (n > rn)
  2357.           n = rn;
  2358.         for (i = 0; i < n; ++i)
  2359.           if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
  2360.         break;
  2361.         for (j = 0; j < i; ++j)
  2362.           lmp->right[j] = lmp->right[(ln - i) + j];
  2363.         lmp->right[j] = '\0';
  2364.         new = inboth(lmp->in, rmp->in);
  2365.         if (new == NULL)
  2366.           goto done;
  2367.         freelist(lmp->in);
  2368.         free((char *) lmp->in);
  2369.         lmp->in = new;
  2370.       }
  2371.       break;
  2372.     case PLUS:
  2373.       if (mp <= musts)
  2374.         goto done;        /* "cannot happen" */
  2375.       --mp;
  2376.       mp->is[0] = '\0';
  2377.       break;
  2378.     case END:
  2379.       if (mp != &musts[1])
  2380.         goto done;        /* "cannot happen" */
  2381.       for (i = 0; musts[0].in[i] != NULL; ++i)
  2382.         if (strlen(musts[0].in[i]) > strlen(result))
  2383.           result = musts[0].in[i];
  2384.       if (strcmp(result, musts[0].is) == 0)
  2385.         exact = 1;
  2386.       goto done;
  2387.     case CAT:
  2388.       if (mp < &musts[2])
  2389.         goto done;        /* "cannot happen" */
  2390.       {
  2391.         must *lmp;
  2392.         must *rmp;
  2393.  
  2394.         rmp = --mp;
  2395.         lmp = --mp;
  2396.         /* In.  Everything in left, plus everything in
  2397.            right, plus catenation of
  2398.            left's right and right's left. */
  2399.         lmp->in = addlists(lmp->in, rmp->in);
  2400.         if (lmp->in == NULL)
  2401.           goto done;
  2402.         if (lmp->right[0] != '\0' &&
  2403.         rmp->left[0] != '\0')
  2404.           {
  2405.         char *tp;
  2406.  
  2407.         tp = icpyalloc(lmp->right);
  2408.         if (tp == NULL)
  2409.           goto done;
  2410.         tp = icatalloc(tp, rmp->left);
  2411.         if (tp == NULL)
  2412.           goto done;
  2413.         lmp->in = enlist(lmp->in, tp,
  2414.                  strlen(tp));
  2415.         free(tp);
  2416.         if (lmp->in == NULL)
  2417.           goto done;
  2418.           }
  2419.         /* Left-hand */
  2420.         if (lmp->is[0] != '\0')
  2421.           {
  2422.         lmp->left = icatalloc(lmp->left,
  2423.                       rmp->left);
  2424.         if (lmp->left == NULL)
  2425.           goto done;
  2426.           }
  2427.         /* Right-hand */
  2428.         if (rmp->is[0] == '\0')
  2429.           lmp->right[0] = '\0';
  2430.         lmp->right = icatalloc(lmp->right, rmp->right);
  2431.         if (lmp->right == NULL)
  2432.           goto done;
  2433.         /* Guaranteed to be */
  2434.         if (lmp->is[0] != '\0' && rmp->is[0] != '\0')
  2435.           {
  2436.         lmp->is = icatalloc(lmp->is, rmp->is);
  2437.         if (lmp->is == NULL)
  2438.           goto done;
  2439.           }
  2440.         else
  2441.           lmp->is[0] = '\0';
  2442.       }
  2443.       break;
  2444.     default:
  2445.       if (t < END)
  2446.         {
  2447.           /* "cannot happen" */
  2448.           goto done;
  2449.         }
  2450.       else if (t == '\0')
  2451.         {
  2452.           /* not on *my* shift */
  2453.           goto done;
  2454.         }
  2455.       else if (t >= CSET)
  2456.         {
  2457.           /* easy enough */
  2458.           resetmust(mp);
  2459.         }
  2460.       else
  2461.         {
  2462.           /* plain character */
  2463.           resetmust(mp);
  2464.           mp->is[0] = mp->left[0] = mp->right[0] = t;
  2465.           mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  2466.           mp->in = enlist(mp->in, mp->is, 1);
  2467.           if (mp->in == NULL)
  2468.         goto done;
  2469.         }
  2470.       break;
  2471.     }
  2472. #ifdef DEBUG
  2473.       fprintf(stderr, " node: %d:", ri);
  2474.       prtok(dfa->tokens[ri]);
  2475.       fprintf(stderr, "\n  in:");
  2476.       for (i = 0; mp->in[i]; ++i)
  2477.     fprintf(stderr, " \"%s\"", mp->in[i]);
  2478.       fprintf(stderr, "\n  is: \"%s\"\n", mp->is);
  2479.       fprintf(stderr, "  left: \"%s\"\n", mp->left);
  2480.       fprintf(stderr, "  right: \"%s\"\n", mp->right);
  2481. #endif
  2482.       ++mp;
  2483.     }
  2484.  done:
  2485.   if (strlen(result))
  2486.     {
  2487.       dm = (struct dfamust *) malloc(sizeof (struct dfamust));
  2488.       dm->exact = exact;
  2489.       dm->must = malloc(strlen(result) + 1);
  2490.       strcpy(dm->must, result);
  2491.       dm->next = dfa->musts;
  2492.       dfa->musts = dm;
  2493.     }
  2494.   mp = musts;
  2495.   for (i = 0; i <= dfa->tindex; ++i)
  2496.     {
  2497.       freelist(mp[i].in);
  2498.       ifree((char *) mp[i].in);
  2499.       ifree(mp[i].left);
  2500.       ifree(mp[i].right);
  2501.       ifree(mp[i].is);
  2502.     }
  2503.   free((char *) mp);
  2504. }
  2505.